package com.zhongpengcheng.blog.event.handler;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSON;
import com.zhongpengcheng.blog.dao.pojo.db.FileDO;
import com.zhongpengcheng.blog.event.FileDeleteEvent;
import com.zhongpengcheng.blog.event.FileUploadEvent;
import com.zhongpengcheng.blog.service.FileService;
import com.zhongpengcheng.blog.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 文件事件处理器
 *
 * @author ZhongPengCheng
 * @version 1.0
 * @since 2021-12-04 21:47:00
 */
@Slf4j
@Component
public class FileEventHandler {

    @Autowired
    private FileService fileService;
    @Autowired
    private Snowflake fileIdGenerator;
    @Autowired
    private OssService ossService;

    /**
     * 文件上传事件后处理
     * @param event 事件对象
     */
    @Async
    @EventListener
    public void onFileUploadPostEvent(FileUploadEvent event) {
        FileDO fileDO = FileDO.builder()
                .fileId(fileIdGenerator.nextIdStr())
                .ossStoragePath(event.getFileUploadRO().getUrl())
                .fileName(event.getFilename())
                .extension(FileUtil.extName(event.getFilename()))
                .build();
        if (!fileService.save(fileDO)) {
            log.error("保存文件到OSS成功，但保存索引信息至数据库失败, event={}", event);
        }
        log.info("新增文件完成, fileDO={}", JSON.toJSONString(fileDO));
    }

    /**
     * 文件删除事件后处理
     * @param event 事件对象
     */
    @Async
    @EventListener
    public void onFileDeletePostEvent(FileDeleteEvent event) {
        boolean success = ossService.delete(event.getPath());
        if (!success) {
            log.error("OSS文件移除失败, event={}", event);
        }
    }
}
